package com.yiqi.liebang.feature.home.view;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.suozhang.framework.framework.BaseActivity;
import com.suozhang.framework.utils.T;
import com.suozhang.framework.utils.logger.Logger;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yiqi.liebang.R;
import com.yiqi.liebang.common.alipay.PayResult;
import com.yiqi.liebang.entity.bo.CouponBo;
import com.yiqi.liebang.entity.bo.PayBo;
import com.yiqi.liebang.entity.enums.OrderType;
import com.yiqi.liebang.feature.home.contract.PayContract;
import com.yiqi.liebang.feature.home.dependencies.pay.DaggerPayComponent;
import com.yiqi.liebang.feature.home.dependencies.pay.PayPresenterModule;
import com.yiqi.liebang.feature.mine.view.SelectCouponActivity;
import com.yiqi.liebang.feature.order.view.OrderInfoActivity;
import com.yiqi.liebang.wxapi.WXPayEntryActivity;

import java.text.DecimalFormat;
import java.util.Map;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.yiqi.liebang.entity.enums.OrderType.HUATI;
import static com.yiqi.liebang.entity.enums.OrderType.WEIGUAN;
import static com.yiqi.liebang.entity.enums.OrderType.WENDA;

public class PayActivity extends BaseActivity implements PayContract.View {

    @Inject
    PayContract.Presenter mPresenter;
    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.iv_pay_alipay)
    ImageView mIvPayAlipay;
    @BindView(R.id.iv_pay_wechat)
    ImageView mIvPayWechat;
    @BindView(R.id.tv_user_register)
    TextView mBtnUserRegister;
    @BindView(R.id.tv_pay_prize)
    TextView mTvPayPrize;
    @BindView(R.id.tv_pay_coupon)
    TextView mTvPayCoupon;
    @BindView(R.id.tv_pay_money)
    TextView mTvPayMoney;
    @BindView(R.id.iv_pay_balance)
    ImageView mIvPayBalance;
    @BindView(R.id.tv_pay_banlance)
    TextView mTvPayBanlance;
    @BindView(R.id.tv_money_count)
    TextView mTvMoneyCount;
    @BindView(R.id.tv_show_pay_type)
    TextView mTvShowPayType;


    private double mAskPrize;
    private String mAskContent;
    private String mLabelsStr;
    CouponBo mCouponBo = null;
    private double mPayPrize;
    private int mPayType;
    private String mAskUserUid;

    private String mTopicAskQuestion;
    private String mAskIntroduction;
    private String topicId;
    private String questionId;
    private int mType;

    private String mOrderid;

    @Override
    protected int attachLayoutRes() {
        return R.layout.activity_pay;
    }

    @Override
    protected void initInjector() {
        DaggerPayComponent.builder().payPresenterModule(new PayPresenterModule(this)).build().inject(this);
    }

    @Override
    protected void initView() {
        initToolBar(mToolbar, "收银台", true, true);
        mAskPrize = getIntent().getDoubleExtra("ask_prize", 0.00);
        mAskContent = getIntent().getStringExtra("ask_content");
        mLabelsStr = getIntent().getStringExtra("ask_lables");
        mAskUserUid = getIntent().getStringExtra("ask_userid");
        mTopicAskQuestion = getIntent().getStringExtra("topicAskQuestion");
        mAskIntroduction = getIntent().getStringExtra("askIntroduction");
        mType = this.getIntent().getIntExtra("order_type", 0);
        topicId = getIntent().getStringExtra("topicId");
        questionId = getIntent().getStringExtra("questionId");

        mTvShowPayType.setText(OrderType.getName(mType));
        IntentFilter filter = new IntentFilter(WXPayEntryActivity.action);
        registerReceiver(broadcastReceiver, filter);
    }

    BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent != null) {
                if (intent.getBooleanExtra("data", false)) {
                    switch (mType) {
                        case 0:
                        case 2:
                            // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                            T.showShort("支付成功");

                            if (mType == WENDA.getIndex()) {
                                Intent intentWENDA = new Intent(PayActivity.this, AskInfoActivity.class);
                                intentWENDA.putExtra("order_id", mOrderid);
                                intentWENDA.putExtra("is_expert", false);
                                startActivity(intentWENDA);
                            } else if (mType == HUATI.getIndex()) {
                                Intent intentHUATI = new Intent(PayActivity.this, OrderInfoActivity.class);
                                intentHUATI.putExtra("id", mOrderid);
                                intentHUATI.putExtra("is_expert", false);
                                startActivity(intentHUATI);
                            }

                            finish();
                            break;
                        case 1:
                            Intent intentS = new Intent();
                            intentS.putExtra("is_ok", true);
                            PayActivity.this.setResult(2, intentS);
                            finish();
                            break;
                    }
                }
            }
        }

    };

    @Override
    protected void initData() {
        mPayPrize = mAskPrize;
        mTvPayPrize.setText("￥" + mAskPrize);
        Drawable drawable = this.getResources().getDrawable(R.drawable.icon_zhifubao);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        mTvPayPrize.setCompoundDrawables(drawable, null, null, null);
        mBtnUserRegister.setText("确认支付" + mPayPrize + "元");
        mPresenter.getUserAssetsDetail(1, 10);
        mTvPayMoney.setText(mPayPrize + "");

    }


    @OnClick({R.id.btn_pay_alipay, R.id.btn_pay_wechat, R.id.btn_pay_coupon, R.id.tv_pay_money, R.id.btn_user_register, R.id.btn_pay_balance})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_pay_alipay:
                mPayType = 0;

                mIvPayAlipay.setImageResource(R.drawable.list_button_select);
                mIvPayWechat.setImageResource(R.drawable.list_btn_normal);
                mIvPayBalance.setImageResource(R.drawable.list_btn_normal);

                break;
            case R.id.btn_pay_wechat:
                mPayType = 1;

                mIvPayAlipay.setImageResource(R.drawable.list_btn_normal);
                mIvPayWechat.setImageResource(R.drawable.list_button_select);
                mIvPayBalance.setImageResource(R.drawable.list_btn_normal);

                break;
            case R.id.btn_pay_balance:
                mPayType = 2;
                mIvPayAlipay.setImageResource(R.drawable.list_btn_normal);
                mIvPayWechat.setImageResource(R.drawable.list_btn_normal);
                mIvPayBalance.setImageResource(R.drawable.list_button_select);
                break;
            case R.id.btn_pay_coupon:
                Intent intent = new Intent(this, SelectCouponActivity.class);
                intent.putExtra("ask_prize", mAskPrize);
                intent.putExtra("ask_lables", mLabelsStr);
                startActivityForResult(intent, 1);
                break;
            case R.id.btn_user_register:
                if (mType == WENDA.getIndex()) {
                    mPresenter.createOrder(WENDA.getIndex(), mAskPrize, mPayPrize, mCouponBo == null ? null :
                            mCouponBo.getId(), mPayType, mAskContent, mAskUserUid, mAskPrize);
                } else if (mType == HUATI.getIndex()) {
                    mPresenter.createTopicOrder(HUATI.getIndex(), mAskPrize, mPayPrize, mCouponBo == null ? null : mCouponBo.getId(),
                            mPayType, mAskUserUid, mAskPrize, mTopicAskQuestion, mAskIntroduction, topicId);
                } else if (mType == WEIGUAN.getIndex()) {
                    mPresenter.createOneLookOrder(WEIGUAN.getIndex(), mAskPrize, mPayPrize, mCouponBo == null ? null : mCouponBo.getId(),
                            mPayType, mAskPrize, questionId);
                }

                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 2) {
            mCouponBo = (CouponBo) data.getSerializableExtra("three");
            if (mCouponBo != null) {
                mTvPayCoupon.setText("-￥" + mCouponBo.getOffMoney());
                mPayPrize = mAskPrize - mCouponBo.getOffMoney();
                mPayPrize = getTwoDecimal(mPayPrize);
                mTvPayMoney.setText(mPayPrize + "");
                mBtnUserRegister.setText("确认支付" + mPayPrize + "元");
            }
        }
    }

    /**
     * 将数据保留两位小数
     */
    private double getTwoDecimal(double num) {
        DecimalFormat dFormat = new DecimalFormat("#.00");
        String yearString = dFormat.format(num);
        Double temp = Double.valueOf(yearString);
        return temp;
    }


    @Override
    public void showSuccess(PayBo classifyBos) {
        mOrderid = classifyBos.getOrderId();
        if (mPayType == 0) {
            toAlipay(classifyBos.getAlipay_url());
        } else if (mPayType == 1) {
            toWxPay(classifyBos.getWxpay_url());
        } else if (mPayType == 2) {
            showMsg("支付成功！");
            switch (mType) {
                case 0:
                case 2:
                    // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                    T.showShort("支付成功");
                    if (mType == WENDA.getIndex()) {
                        Intent intentWENDA = new Intent(PayActivity.this, AskInfoActivity.class);
                        intentWENDA.putExtra("order_id", mOrderid);
                        intentWENDA.putExtra("is_expert", false);
                        startActivity(intentWENDA);
                    } else if (mType == HUATI.getIndex()) {
                        Intent intentHUATI = new Intent(PayActivity.this, OrderInfoActivity.class);
                        intentHUATI.putExtra("id", mOrderid);
                        intentHUATI.putExtra("is_expert", false);
                        startActivity(intentHUATI);
                    }
                    finish();
                    break;
                case 1:
                    Intent intent = new Intent();
                    intent.putExtra("is_ok", true);
                    setResult(2, intent);
                    finish();
                    break;
            }
        }
    }

    @Override
    public void showError(String ex) {
        showMsg(ex);
    }

    @Override
    public void showBanlanceSuccess(String error) {
        mTvPayBanlance.setText(TextUtils.isEmpty(error) ? "" : "余额：" + error + "元");
    }

    private void toWxPay(PayBo.WechatBo wxPayBo) {
        IWXAPI api = WXAPIFactory.createWXAPI(this, wxPayBo.getAppid());
        api.registerApp(wxPayBo.getAppid());
        PayReq req = new PayReq();
        req.appId = wxPayBo.getAppid();
        req.partnerId = wxPayBo.getPartnerid();
        req.prepayId = wxPayBo.getPrepayid();
        req.nonceStr = wxPayBo.getNoncestr();
        req.timeStamp = wxPayBo.getTimestamp();
        req.packageValue = "Sign=WXPay";
        req.sign = wxPayBo.getSign();
        api.sendReq(req);
    }

    /**
     * 支付宝支付
     */
    private void toAlipay(String msg) {

        Runnable payRunnable = new Runnable() {

            @Override
            public void run() {
                PayTask alipay = new PayTask(PayActivity.this);
                Map<String, String> result = alipay.payV2(msg, true);
                Logger.e("msg-------->", result.toString());
                Message msg = new Message();
                msg.what = SDK_PAY_FLAG;
                msg.obj = result;
                mHandler.sendMessage(msg);
            }
        };
        // 必须异步调用
        Thread payThread = new Thread(payRunnable);
        payThread.start();
    }

    private static final int SDK_PAY_FLAG = 1;
    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    @SuppressWarnings("unchecked")
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        switch (mType) {
                            case 0:
                            case 2:
                                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                                T.showShort("支付成功");
                                if (mType == WENDA.getIndex()) {
                                    Intent intentWENDA = new Intent(PayActivity.this, AskInfoActivity.class);
                                    intentWENDA.putExtra("order_id", mOrderid);
                                    intentWENDA.putExtra("is_expert", false);
                                    startActivity(intentWENDA);
                                } else if (mType == HUATI.getIndex()) {
                                    Intent intentHUATI = new Intent(PayActivity.this, OrderInfoActivity.class);
                                    intentHUATI.putExtra("id", mOrderid);
                                    intentHUATI.putExtra("is_expert", false);
                                    startActivity(intentHUATI);
                                }
                                finish();
                                break;
                            case 1:
                                Intent intent = new Intent();
                                intent.putExtra("is_ok", true);
                                setResult(2, intent);
                                finish();
                                break;
                        }

                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                        T.showShort("支付失败");
                    }
                    break;
                }
                default:
                    break;
            }
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (broadcastReceiver != null) {
            unregisterReceiver(broadcastReceiver);
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
